package com.reger.test.user.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.github.pagehelper.PageHelper;
import com.reger.datasource.annotation.DataSourceChange;
import com.reger.test.user.dao.UserMapper;
import com.reger.test.user.enums.State;
import com.reger.test.user.model.User;
import com.reger.test.user.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	
	private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	@Transactional("user")
	public void delAll() {
		User user=new User();
		user.setState(State.enable);
		int num=userMapper.delete(user);
		log.info("成功删除{}条数据！",num);
	}

	@Override
	@Transactional("user")
	@DataSourceChange(slave=false) //更新操作必须在主库执行
	public void save(String name, String description) {
		User record=new User();
		record.setName(name);
		record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		record.setState(State.enable);
		record.setDescription(description);
		log.info("{}",record);
		int num=userMapper.insertSelective(record);
		Assert.isTrue(num==1, "插入数据失败");
	}

	@Override
	public List<User> findAll() {
		return userMapper.selectAll();
	}
	
	@Override
	@DataSourceChange(slave=true)
	public List<User> findAllBySlave() {
		return this.findAll();
	}
	
	@Override
	public User findFirst() {
		User user=new User();
		PageHelper.startPage(1, 1, " name desc");
		return userMapper.selectOne(user);
	}
	@Override
	@DataSourceChange(slave=true)
	public User findFirstBySlave() {
		return this.findFirst();
	}

	@Override
	public void saves(String... names) {
		List<User> recordList=new ArrayList<>();
		for (String name : names) {
			User record=new User();
			record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			record.setName(name);
			record.setState(State.disable);
			record.setDescription("这是批量插入的数据");
			recordList.add(record);
		}
		int num=userMapper.insertList(recordList);
		log.info("成功保存 {} 个",num);
	}
}
